captcha javascript w3schools

Addcaptcha

Creating a simple CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart) in JavaScript can be achieved using various techniques. In this example, we'll create a basic CAPTCHA using W3Schools as a reference.


HTML:

```html




Simple CAPTCHA Example



Simple CAPTCHA Example













```


JavaScript (captcha.js):

```javascript

// Generate a random CAPTCHA code

function generateCaptchaCode() {

const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

const length = 6;

let captchaCode = '';

for (let i = 0; i < length; i++) {

captchaCode += characters.charAt(Math.floor(Math.random() characters.length));

}

return captchaCode;

}


// Draw the CAPTCHA on the canvas

function drawCaptcha() {

const canvas = document.getElementById('captchaCanvas');

const context = canvas.getContext('2d');


context.clearRect(0, 0, canvas.width, canvas.height);


const captchaCode = generateCaptchaCode();

const fontSize = 30;

const x = 20;

const y = 35;


context.font = `${fontSize}px Arial`;

context.fillText(captchaCode, x, y);


// Store the generated CAPTCHA code in a hidden field for validation

document.getElementById('captchaInput').dataset.captchaCode = captchaCode;

}


// Initialize the CAPTCHA when the page loads

drawCaptcha();


// Validate the user's input

function validateCaptcha() {

const userInput = document.getElementById('captchaInput').value;

const actualCaptchaCode = document.getElementById('captchaInput').dataset.captchaCode;


if (userInput === actualCaptchaCode) {

alert('CAPTCHA verification successful. You may proceed!');

drawCaptcha(); // Generate a new CAPTCHA for the next submission

return false; // Prevent form submission for this example

} else {

alert('Incorrect CAPTCHA code. Please try again.');

drawCaptcha(); // Generate a new CAPTCHA for the next attempt

return false; // Prevent form submission for this example

}

}

```


This code will create a simple CAPTCHA system where a random alphanumeric code of length 6 is generated and displayed on a canvas. The user needs to enter the correct code in the input field to pass the CAPTCHA verification. If the user's input matches the displayed code, a success message will be displayed, and a new CAPTCHA will be generated for the next submission. If the input is incorrect, an error message will appear, and a new CAPTCHA will be provided for the user to try again.


Please note that this example is just for educational purposes and should not be used for serious security applications. Real-world CAPTCHAs often involve more complex algorithms and techniques to prevent automated attacks effectively.